﻿namespace Revit同步插件
{
  using Autodesk.Revit.DB;
  using Autodesk.Revit.UI;


  /// <summary>
  /// 同步外部命令
  /// </summary>
  [Autodesk.Revit.Attributes.Transaction(Autodesk.Revit.Attributes.TransactionMode.Manual)]
  class Rommand : IExternalCommand
  {


    UIApplication _uiapp;
    public Autodesk.Revit.UI.Result Execute(Autodesk.Revit.UI.ExternalCommandData commandData,
    ref string message,
    Autodesk.Revit.DB.ElementSet elements)
    {

      try
      {
        _uiapp = commandData.Application;
        UIDocument uidoc = _uiapp.ActiveUIDocument;
        Document doc = uidoc.Document;

       int status = 与中心文件同步(doc);
        TaskDialog td = new TaskDialog("自动同步");
        
        switch (status)
        {
          case 0:
            td.MainContent = "同步失败！";
            break;
          case 1:
            td.MainContent = "同步完成！";
            break;
          case -1:
            td.MainContent = "中文文件正在被锁定。请稍后再试...";
            break;
        }

        td.Show();

        return Autodesk.Revit.UI.Result.Succeeded;
      }
      catch (System.Exception ex)
      {
        message = ex.Message;
        return Autodesk.Revit.UI.Result.Failed;
      }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="doc"></param>
    /// <returns>1 成功，0失败，-1：中心文件已被锁定</returns>
    int 与中心文件同步(Document doc)
    {
      TransactWithCentralOptions 中心文件传输选项 = new TransactWithCentralOptions();
      锁放弃同步 同步锁处理 = new 锁放弃同步();
      中心文件传输选项.SetLockCallback(同步锁处理);

      SynchronizeWithCentralOptions 同步选项 = new SynchronizeWithCentralOptions();
      RelinquishOptions 放弃权限选项 = new RelinquishOptions(true); // 放弃所有权限
      同步选项.SetRelinquishOptions(放弃权限选项);
      同步选项.Comment = "自动同步";
      try
      {
        doc.SynchronizeWithCentral(中心文件传输选项, 同步选项);
        return 1;
      }
      catch (Autodesk.Revit.Exceptions.CentralModelContentionException 中心文件被锁定异常)
      {
        return -1;
      }
      catch (System.Exception)
      {
        return 0;
      }
    }
  }



  class 锁放弃同步 : ICentralLockedCallback
  {
    public bool ShouldWaitForLockAvailability()
    {
      return false;
    }
  }
}
